<template>
  <el-card class="mt15 mb15">
    <div class="search-filter">
      <el-row :gutter="20">
        <el-col :span="6">
          <sitem label="企业名称：">
            <el-input
              slot="item"
              v-model="listQuery.enName"
              placeholder="请输入关键字"
              @input="handleFilter"
            />
          </sitem>
        </el-col>
        <el-col :span="6">
          <sitem label="所在地（省市）：">
            <el-cascader slot="item" v-model="listQuery.areaData" :options="areaData" @change="handleFilter" />
          </sitem>
        </el-col>
        <el-col :span="6">
          <sitem label="行业：">
            <el-cascader slot="item" v-model="listQuery.enTrades" :options="tradeData" @change="handleFilter" />
          </sitem>
        </el-col>
        <el-col :span="6">
          <sitem label="企业性质：">
            <el-select slot="item" v-model="listQuery.enNature" clearable placeholder="请选择" @change="handleFilter">
              <el-option v-for="(item,index) in enNature" :key="index" :label="item" :value="item" />
            </el-select>
          </sitem>
        </el-col>
        <el-col :span="6">
          <sitem label="专场：">
            <el-select slot="item" v-model="listQuery.ssSessionId" clearable placeholder="请选择" @change="handleFilter">
              <el-option v-for="(item,index) in ssSessionOptions" :key="index" :label="item.itemText" :value="item.itemValue" />
            </el-select>
          </sitem>
        </el-col>
        <el-col :span="6">
          <sitem label="审核状态：">
            <el-select slot="item" v-model="listQuery.state" clearable placeholder="请选择" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="通过" value="0" />
              <el-option label="未审核" value="1" />
              <el-option label="未通过" value="2" />
            </el-select>
          </sitem>
        </el-col>
        <!-- <el-col :span="6">
          <sitem label="是否自主注册：">
            <el-select slot="item" v-model="listQuery.actFlag" clearable placeholder="请选择" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </sitem>
        </el-col> -->
        <el-col :span="6">
          <sitem label="在招职位数：" range>
            <el-input
              slot="low"
              v-model="listQuery.post[0]"
              oninput="value=value.replace(/[^\d]/g,'')"
              max-length="9"
              placeholder="填写整数"
            /><el-input
              slot="high"
              v-model="listQuery.post[1]"
              oninput="value=value.replace(/[^\d]/g,'')"
              max-length="9"
              placeholder="填写整数"
              @keyup.enter.native="handleFilter"
            />
          </sitem>
        </el-col>
        <!-- <el-col :span="6">
          <sitem label="简历投递量：" range>
            <el-input
              slot="low"
              v-model="listQuery.deliver[0]"
              oninput="value=value.replace(/[^\d]/g,'')"
              max-length="9"
              placeholder="填写整数"
            /><el-input
              slot="high"
              v-model="listQuery.deliver[1]"
              oninput="value=value.replace(/[^\d]/g,'')"
              max-length="9"
              placeholder="填写整数"
              @keyup.enter.native="handleFilter"
            />
          </sitem>
        </el-col> -->
        <!-- <el-col :span="6">
          <sitem label="反馈率（%）：" range>
            <el-input
              slot="low"
              v-model="listQuery.feed[0]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
            /><el-input
              slot="high"
              v-model="listQuery.feed[1]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
              @keyup.enter.native="handleFilter"
            />
          </sitem>
        </el-col> -->
        <!-- <el-col :span="6">
          <sitem label="面试率（%）：" range>
            <el-input
              slot="low"
              v-model="listQuery.interview[0]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
            />-<el-input
              slot="high"
              v-model="listQuery.interview[1]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
              @keyup.enter.native="handleFilter"
            />
          </sitem>
        </el-col> -->
        <!-- <el-col :span="6">
          <sitem label="入职率（%）：" range>
            <el-input
              slot="low"
              v-model="listQuery.induction[0]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
            />-<el-input
              slot="high"
              v-model="listQuery.induction[1]"
              oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
              max-length="9"
              placeholder="填写数字"
              @keyup.enter.native="handleFilter"
            />
          </sitem>
        </el-col> -->
        <el-col :span="6">
          <sitem label="">
            <el-button slot="item" v-waves type="primary" icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
          </sitem>
        </el-col>
      </el-row>
    </div>
    <div class="mb15">
      <el-button type="primary" icon="el-icon-document-add" @click="drawOpen('新增')">新增</el-button>
      <!-- 2021年1月7日18:09:50 因为bug 临时 干掉删除功能
     <el-button type="danger" icon="el-icon-document-delete" @click="delMultiple">删除</el-button>
     -->
      <el-popover
        class="ml5"
        placement="bottom-start"
        trigger="hover"
        @show="exportListShow(name + '_企业管理_导出')"
      >
        <el-table
          v-loading="popoverLoading"
          :data="exportListData"
          style="width: 100%"
        >
          <el-table-column
            prop="createTime"
            label="导出时间"
            width="160"
          />
          <el-table-column
            prop="state_dictText"
            label="状态"
          />
          <el-table-column
            prop="duration"
            label="耗时"
          />
          <el-table-column
            label="下载地址"
            width="310"
          >
            <template slot-scope="{row}">
              <el-link v-if="row.url" type="primary" :href="row.url" target="_blank">
                {{ row.url.substring(row.url.lastIndexOf('/') + 1) }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column
            prop="duration"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-popconfirm title="确定删除吗？" @onConfirm="exportDelete(row.id)">
                <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" circle />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button slot="reference" type="primary" icon="el-icon-user" @click="exportResume">导出</el-button>
      </el-popover>
    </div>
    <el-table
      :key="tableKey"
      ref="companyList"
      v-loading="listLoading"
      :data="list"
      fit
      stripe
      highlight-current-row
      style="width: 100%;"
    >
      <!-- @sort-change="sortChange" -->
      <el-table-column
        type="selection"
        width="50"
      />
      <el-table-column label="企业" prop="enName" align="center" width="120px" />
      <el-table-column label="所在地" prop="enAddress_dictText" align="center" width="120px" />
      <el-table-column label="行业" prop="enTrade_dictText" width="120px" align="center" />
      <el-table-column label="企业性质" prop="enNature" width="80px" align="center" />
      <el-table-column label="专场" prop="ssSessionId_dictText" width="80px" align="center" />
      <el-table-column label="审核状态" width="80px" align="center">
        <template slot-scope="{row}">
          {{ row.state | stateFilter }}
        </template>
      </el-table-column>
      <el-table-column label="是否自主注册" width="120px" align="center">
        <template slot-scope="{row}">
          {{ row.actFlag?'是':'否' }}
        </template>
      </el-table-column>
      <el-table-column label="在招职位数" prop="postNum" width="100px" align="center" />
      <el-table-column label="简历投递量" prop="deliverNum" width="100px" align="center" />
      <el-table-column label="反馈率" prop="feedAck" width="80px" align="center" />
      <el-table-column label="面试率" prop="interviewRate" width="80px" align="center" />
      <el-table-column label="入职率" prop="inductionRate" width="80px" align="center" />
      <el-table-column label="操作" align="center" width="160px" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="{row,index}">
          <el-button type="text" @click="drawOpen('查看',row)">
            查看
          </el-button>
          <el-button type="text" @click="drawOpen('编辑',row)">
            编辑
          </el-button>
          <!-- <el-button type="text" @click="drawOpen(row)">
            更多
          </el-button> -->
          <el-dropdown trigger="click">
            <span class="el-dropdown-link el-button--text pl10">
              <span>更多</span><i class="el-icon-caret-bottom" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item class="clearfix">
                <el-button v-if="row.state" type="text" @click="drawOpen('审核',row)">
                  审核
                </el-button>
                <!-- <el-button v-else type="text" disabled>
                  已审核
                </el-button> -->
              </el-dropdown-item>
              <!-- 2021年1月7日18:09:50 因为bug 临时 干掉删除功能-->
              <el-dropdown-item class="clearfix">
                <el-button type="text" @click="delItem(row,index)">
                  <span class="el-link el-link--danger">删除</span>
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item class="clearfix">
                <el-button type="text" @click="disItem(row,index)">
                  <template v-if="!row.banFlag">
                    <span class="el-link el-link--success">启用</span>
                  </template>
                  <template v-else>
                    <span class="el-link el-link--warning">禁用</span>
                  </template>
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
      layout="total,prev, pager, next, jumper"
      :page.sync="listQuerytrue.pageNo"
      :limit.sync="listQuerytrue.pageSize"
      @pagination="getList"
    />

    <edit-drawer ref="editDrawer" @refresh="refresh" />

    <view-drawer ref="viewDrawer" :is-examine="isExamine" @refresh="refresh" />

  </el-card>
</template>

<script>
import { companyList, companyDel, enableOrDisable } from '@/api/vip-company'
import { sys_dict_by_code } from '@/api/sys_dict'
import { exportDelete, exportList } from '@/api/export'
import { downloadEnListInfo } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import editDrawer from './components/editDrawer'
import viewDrawer from './components/viewDrawer'
import sitem from '@/components/searchItem'
import { mapState,mapGetters } from 'vuex'
import store from '@/store'
export default {
  components: { Pagination, editDrawer, viewDrawer, sitem },
  directives: { waves },
  filters: {
    stateFilter(e) {
      if (!e) {
        return '通过'
      } else if (e == 1) {
        return '未审核'
      } else {
        return '未通过'
      }
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        enName: '',
        areaData: [],
        enTrades: [],
        enNature: '',
        state: '',
        actFlag: '',
        post: [],
        deliver: [],
        feed: [],
        interview: [],
        induction: []
      },
      listQuerytrue: {
        pageNo: 1,
        pageSize: 10,
        sort: false,
        enName: '',
        enAddress: '',
        enTrade: '',
        enNature: '',
        state: '',
        actFlag: '',
        postNum: '',
        deliverNum: '',
        feedAck: '',
        interviewRate: '',
        inductionRate: ''
      },
      restaurants: [],
      state: '',
      timeout: null,
      value: '',
      isExamine: false,
      areaData: [],
      tradeData: [],
      ssSessionOptions: [],
      exportListData: [],
      popoverLoading: false
    }
  },
  computed: {
    ...mapState({
      enNature: state => state.app.enNature
    }),
    ...mapGetters(['name']),
  },
  watch: {
    listQuery: {
      handler(n, o) {
        if (n) {
          for (var k in n) {
            if (!Array.isArray(n[k])) {
              this.listQuerytrue[k] = n[k]
            }
          }
          // if (this.listQuerytrue.enName) this.listQuerytrue.enName = '*' + this.listQuerytrue.enName + '*'
          n.areaData.length ? this.listQuerytrue.enAddress = n.areaData.join(',') : this.listQuerytrue.province = ''
          n.enTrades.length ? this.listQuerytrue.enTrade = n.enTrades.join(',') : this.listQuerytrue.enTrade = ''
          const post = [...(n.post)]
          const deliver = [...(n.deliver)]
          const feed = [...(n.feed)]
          const interview = [...(n.interview)]
          const induction = [...(n.induction)]
          !post[0] ? post[0] = 0 : null
          !post[1] ? post[1] = 999999 : null
          !deliver[0] ? deliver[0] = 0 : null
          !deliver[1] ? deliver[1] = 999999 : null
          !feed[0] ? feed[0] = 0 : null
          !feed[1] ? feed[1] = 100 : null
          !interview[0] ? interview[0] = 0 : null
          !interview[1] ? interview[1] = 100 : null
          !induction[0] ? induction[0] = 0 : null
          !induction[1] ? induction[1] = 100 : null
          this.listQuerytrue.postNum = post.join(',')
          this.listQuerytrue.deliverNum = deliver.join(',')
          this.listQuerytrue.feedAck = feed.join(',')
          this.listQuerytrue.interviewRate = interview.join(',')
          this.listQuerytrue.inductionRate = induction.join(',')
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    sys_dict_by_code('gxt_ss_session').then(res => {
      this.ssSessionOptions = res.result
    })
    this.getList()
    // 城市数据
    if (this.$store.state.app.areaData.length === 0) {
      const res = await store.dispatch('app/getArea', 'area')
      this.areaData = JSON.parse(JSON.stringify(res.result))
      if (!this.areaData[0].label !== '全部') {
        this.areaData.unshift({ label: '全部', value: '' })
      }
    } else {
      this.areaData = JSON.parse(JSON.stringify(this.$store.state.app.areaData))
      if (this.areaData[0].label !== '全部') {
        this.areaData.unshift({ label: '全部', value: '' })
      }
    }
    // 行业数据
    if (this.$store.state.app.tradeData.length === 0) {
      const res = await store.dispatch('app/getTrade', 'industry')
      this.tradeData = JSON.parse(JSON.stringify(res.result))
      if (this.tradeData[0].label !== '全部') {
        this.tradeData.unshift({ label: '全部', value: '' })
      }
    } else {
      this.tradeData = JSON.parse(JSON.stringify(this.$store.state.app.tradeData))
      if (this.tradeData[0].label !== '全部') {
        this.tradeData.unshift({ label: '全部', value: '' })
      }
    }
  },
  methods: {
    exportListShow(from) {
      this.popoverLoading = true
      exportList({ from: from }).then(response => {
        this.popoverLoading = false
        if (response.success) {
          this.exportListData = response.result
        }
      })
    },
    exportDelete(id) {
      exportDelete({ id: id }).then(response => {
        if (response.success) {
          this.$message.success('删除成功')
        } else {
          this.$message.warning(response.message)
        }
      })
    },
    exportResume() {
      const ids = []
      const selected = this.$refs.companyList.selection
      selected.forEach(item => {
        ids.push(item.id)
      })
      let parms = null
      if (ids.length) {
        parms = { id: ids.join(',') }
      } else {
        parms = this.listQuerytrue
      }
      parms.from = name + '_企业管理_导出'
      this.exportResumeAction(parms)
    },
    exportResumeAction(parms) {
      downloadEnListInfo(parms).then(response => {
        if (response.success) {
          this.$message.success('任务建立成功')
          this.exportListShow(parms.from)
        } else {
          this.$message.error('任务建立失败')
        }
      })
    },
    // 分页数据
    getList() {
      this.listLoading = true
      companyList(this.listQuerytrue).then(response => {
        this.list = response.result.records
        this.total = response.result.total
        console.log('122', this.total)
        this.listLoading = false
      })
    },
    // 搜索
    handleFilter() {
      this.listQuerytrue.pageNo = 1
      this.getList()
    },
    // 抽屉打开
    drawOpen(title, rowData) {
      if (title === '查看') {
        this.isExamine = false
        this.$refs.viewDrawer.show(title, rowData)
      } else if (title === '审核') {
        this.isExamine = true
        this.$refs.viewDrawer.show(title, rowData)
      } else {
        this.$refs.editDrawer.show(title, rowData)
      }
    },
    // 禁用
    disItem(rowData) {
      if (rowData.banFlag) {
        this.$confirm('禁用后，用户将不能登录，请谨慎操作！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.enableOrDisableCompony(rowData)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消禁用'
          })
        })
      } else {
        this.enableOrDisableCompony(rowData)
      }
    },
    enableOrDisableCompony(rowData) {
      enableOrDisable({ id: rowData.id }).then(response => {
        this.$message({
          type: 'success',
          message: !rowData.banFlag ? '已启用' : '已禁用'
        })
        this.refresh()
      })
    },
    // 删除多个
    delMultiple() {
      const selected = this.$refs['companyList'].selection
      var selected_arr = []
      selected.forEach(item => {
        selected_arr.push(item.id)
      })
      this.$confirm('删除企业将会一并将企业相关的数据一并删除，请谨慎', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delCompony(selected_arr.join(','))
        // this.list.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除一个
    delItem(rowData, index) {
      this.$confirm('删除企业将会一并将企业相关的数据一并删除，请谨慎', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delCompony(rowData.id)
        // this.list.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除方法
    delCompony(id) {
      companyDel({ id: id }).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.refresh()
      })
    },
    refresh() {
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
  .filter-container{
    line-height: 36px;
    font-size: 14px;
    margin-bottom: 10px;
    .filter-item{
      margin-bottom: 0;
    }
  }
</style>
